package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

/**
 * @Author: bowen
 * @Date: 2019/7/16 15:53
 * @Description:实现预约设置
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

	@Autowired
	OrderSettingDao orderSettingDao;

	/**
	 *  @描述：上传模板文件
	 * @param
	 */
	@Override
	public void upload(List<OrderSetting> list) throws IOException {

		if(!CollectionUtils.isEmpty(list)){
			list.forEach(orderSetting->{
			////	将String数组转换成OrderSetting对象
			//	OrderSetting orderSetting = new OrderSetting();
			//	//LocalDate
			//	orderSetting.setOrderDate(new Date(item[0]));
			//	orderSetting.setNumber(Integer.parseInt(item[1]));
			//	判断所选日期是否已经设置（t_ordersetting表有没有记录），如果已经设置，就是更新。如果没有设置，就是插入
				addOrUpdateNumberByOrderDate(orderSetting);
			});


		}

	}


	/**
	 *  @描述：获取预约数据
	 */
	@Override
	public List<Map> getOrdersettingData(String month) {
		List<Map> resultMap = new ArrayList<>();
		//2019-7
		//第一天的字符串
		String begin = month+"-1"; //2019-7-1
		//最后一天的字符串
		String end = month+"-31";
		 List<OrderSetting> orderSettingList = orderSettingDao.getOrdersettingData(begin,end);
		 if(!CollectionUtils.isEmpty(orderSettingList)){
			 orderSettingList.forEach(orderSetting -> {
				 Map hashMap = new HashMap();
				 hashMap.put("date",orderSetting.getOrderDate().getDate());
				 hashMap.put("number",orderSetting.getNumber());
				 hashMap.put("reservations",orderSetting.getReservations());
				 resultMap.add(hashMap);
			 });
		 }
		 return resultMap;
	}

	/**
	 *  @描述：根据日期设置预约数据
	 */
	@Override
	public void setNumberByOrderDate(OrderSetting orderSetting) {
		addOrUpdateNumberByOrderDate(orderSetting);
	}

    /**
     *  @描述：新增或者更新预约数据
     */
	private void addOrUpdateNumberByOrderDate(OrderSetting orderSetting) {
		long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
		if(count > 0){
			//	更新
			orderSettingDao.update(orderSetting);

		} else {
			//	新增
			orderSettingDao.add(orderSetting);
		}
	}

	/**
	 * 定时删除预约设置数据
	 */
	@Override
	public void clearOSAtOneTime() {
		orderSettingDao.clearOSAtOneTime();
	}
}
